package com.nabi.starter.common.exception;


import cn.hutool.json.JSONUtil;

import java.util.Map;


/**
 * 自定义异常
 *
 * @author theodo
 * @email 36780272@qq.com
 * @date 2017年10月27日 下午10:11:27
 */
public class ApiException extends RuntimeException {


    private static final long serialVersionUID = 1L;

    protected ErrorCode code;

    public ApiException(String msg) {
        this(ApiCode.BUSINESS_ERR, msg);
    }

    public ApiException(Integer code, String msg) {
        this(new ApiCode(code, msg));
    }


    public ApiException(ErrorCode code) {
        super(JSONUtil.toJsonStr(code));
        this.code = code;
    }


    public ApiException(ErrorCode code, String message) {
        this(code.getCode(), message);
    }

    public ApiException(String message, Throwable e) {
        this(ApiCode.SYSTEM_ERR, e.getMessage());
    }


    public ApiException(ErrorCode code, Throwable e) {
        super(JSONUtil.toJsonStr(code), e);
        this.code = code;
    }

    public ApiException(ErrorCode apiCode, String message, Throwable e) {
        this(new ApiCode(apiCode), e);
    }

    public ApiException(Throwable e) {
        this(ApiCode.SYSTEM_ERR, e.getMessage());
    }


    public ErrorCode getCode() {
        return code;
    }

    public static ApiException read(String json) {
        try {
            Map map = JSONUtil.parseObj(json);
            Integer code = (Integer) map.get("constant");
            String msg = (String) map.get("msg");
            Integer errorCode = (Integer) map.get("errorCode");
            String errorMsg = (String) map.get("errorMsg");
            return new ApiException(new ApiCode(code, msg, errorCode, errorMsg));
        } catch (Exception e) {
            return new ApiException(ApiCode.SYSTEM_ERR, json);
        }
    }
}
